package com.bskj.sj.controller;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.bskj.common.bean.model.ShortUrl;
import com.bskj.common.bean.model.WxMenu;
import com.bskj.common.cache.mapCache.WxMenuCache;
import com.bskj.common.enums.BmsUserTypeEnum;
import com.bskj.common.utils.LogUtils;
import com.bskj.common.utils.StringUtils;
import com.bskj.sj.service.IShortUrlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ForwardAction {

	@Autowired
	private IShortUrlService shortUrlService;

	@RequestMapping("/action/do")
	public ModelAndView action(@RequestParam String uri, HttpServletRequest req) throws Exception {
		LogUtils.debug(JSONObject.toJSONString(req.getParameterMap()));
		ModelAndView mv = new ModelAndView();
		WxMenu wxMenu = WxMenuCache.get(uri);
		// uri为微信菜单
		if (wxMenu != null) {
			String type = req.getParameter("type");
			if (type != null) {
				if (!(Integer.parseInt(type) == BmsUserTypeEnum.parking_lot_user.getKey())) {
					boolean havePrivilege = havePrivilege("2", wxMenu);
					if (!havePrivilege) {
						mv.setViewName("/auth/nopermission");
						mv.addObject("mag", "物业管理员");
						return mv;
					}
				} else {
					boolean havePrivilege = havePrivilege("1", wxMenu);
					if (!havePrivilege) {
						mv.setViewName("/auth/nopermission");
						mv.addObject("mag", "商店用户");
						return mv;
					}
				}
			}
		}
		mv.setViewName("forward:" + uri);
		return mv;
	}

	@RequestMapping("/shortUrl/{shortUrl}")
	public ModelAndView shortUrl(@PathVariable String shortUrl, HttpServletRequest req) throws Exception {
		ModelAndView mv = new ModelAndView();
		ShortUrl redirectUrl = shortUrlService.getById(shortUrl);
		LogUtils.debug(JSONObject.toJSONString(redirectUrl));
		mv.setViewName("redirect:" + redirectUrl.getActionUrl());
		return mv;
	}

	/**
	 * @param type
	 *            1:停车场id，2:商户id
	 * @param wxMenu
	 * @return
	 */
	private boolean havePrivilege(String type, WxMenu wxMenu) {
		LogUtils.debug(type + "," + JSONObject.toJSONString(wxMenu));
		String roleType = wxMenu.getRoleType();
		if (StringUtils.isBank(roleType)) {
			return true;
		}
		if (roleType.indexOf(type) >= 0) {
			return true;
		}
		return false;
	}
}
